﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Web.Mvc;

using ComLib.Entities;
using ComLib.Authentication;
using ComLib.Web.Lib.Models;
using ComLib.Web.Lib.Extensions;


namespace ComLib.Web.Lib.Helpers
{
    public class ViewHelper
    {
        /// <summary>
        /// Builds the view model.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="view">The view.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="controlPath">The control path.</param>
        /// <param name="useForm">if set to <c>true</c> [use form].</param>
        /// <param name="conf">The conf.</param>
        public static void BuildViewModel<T>(EntityBaseViewModel view, T entity, string controlPath, bool useForm, IDictionary conf) where T: IEntity
        {
            var modelname = typeof(T).Name;
            var editUrl = "/" + modelname + "/edit/";
            var deleteUrl = "/" + modelname + "/delete/";
            var indexUrl = "/" + modelname + "/index/";
            var manageUrl = "/" + modelname + "/manage/";
            bool allowEdit = false;

            if (entity != null)
            {
                editUrl += entity.Id;
                deleteUrl += entity.Id;
                allowEdit = Auth.IsUserOrAdmin(entity.CreateUser);
            }
            view.Name = modelname;
            view.UrlEdit = editUrl;
            view.UrlDelete = deleteUrl;
            view.UrlIndex = indexUrl;
            view.UrlManage = manageUrl;
            view.AllowDelete = allowEdit;
            view.AllowDelete = allowEdit;
            view.ControlPath = controlPath;
            view.Config = conf;
            if (view is EntityDetailsViewModel)
                ((EntityDetailsViewModel)view).Entity = entity;
            else if (view is EntityFormViewModel)
                ((EntityFormViewModel)view).Entity = entity;
        }
    }
}
